<template>
  <div>
    <h1>
      Roles页面
    </h1>

    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="box-card">
      <el-row>
        <el-col> <el-button type="primary" @click="addRoles">添加角色</el-button> </el-col>
      </el-row>

      <el-table :data="rolesList" style="width: 100%" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand" width="50px">
          <template slot-scope="scope">
            <el-row :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'RolesL']" v-for="(item1, i1) in scope.row.children" :key="item1.id">
              <!-- 一行24，前一级权限，后二级和三级权限 -->
              <el-col :span="5">
                <el-tag @close="removeRightsById(scope.row.id, item1.id)">{{ item1.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>

              <el-col :span="19">
                <el-row :class="[i2 === 0 ? '' : 'bdtop', 'RolesL']" v-for="(item2, i2) in item1.children" :key="item2.id">
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeRightsById(scope.row.id, item2.id)">{{ item2.authName }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>

                  <el-col :span="18">
                    <el-tag type="warning" v-for="item3 in item2.children" :key="item3.id" closable @close="removeRightsById(scope.row.id, item3.id)">
                      {{ item3.authName }}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <pre>
                {{ scope.row.children }}
              </pre
            >
          </template>
        </el-table-column>

        <el-table-column type="index" label="#"> </el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <el-table-column prop="level" label="操作" width="300px">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="eidtDiglog(scope.row.id)">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserbyId(scope.row.id, scope.row.username)">删除</el-button>
            <el-tooltip effect="dark" content="分配角色" placement="top-start" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRightDialog(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 用户列表区 -->
    <el-dialog title="添加用户" :visible.sync="addrolesVisible" width="50%">
      <el-form :model="addrolesForm" :rules="addrolesFormRules" ref="addrolesFormRef" label-width="70px" class="demo-ruleForm">
        <el-form-item label="用户名" prop="rolesname">
          <el-input v-model="addrolesForm.rolesname"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addrolesForm.password"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addrolesVisible = false">取 消</el-button>
        <el-button type="primary" @click="addrolesVisible = false">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色 -->
    <el-dialog title="分配权限" :visible.sync="setRightDialogVisible" width="50%">
      <!-- 树形控件 -->
      <el-tree :data="rightsList" show-checkbox mode-key="id" ref="treeRef" node-key="id" default-expand-all :props="treeProps" :default-checked-keys="defKeys"></el-tree>

      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      rolesList: [],
      addrolesVisible: false,

      addrolesForm: {
        rolesname: '',
        rolespassword: ''
      },

      addrolesFormRules: {
        rolesname: [],
        rolespassword: []
      },

      rightsList: [],
      setRightDialogVisible: false,

      treeProps: {
        label: 'authName',
        children: 'children'
      },

      defKeys: [],
      roleId: ''
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')

      if (res.meta.status !== 200) {
        this.$message.error('数据渲染失败')
      }
      this.rolesList = res.data
    },

    addRoles() {
      this.addrolesVisible = true
    },

    // 权限展开相关
    async removeRightsById(RoleId, Rightsid) {
      const confirmResult = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      if (confirmResult !== 'confirm') {
        this.$message.info('已经取消了')
      }

      const { data: res } = await this.$http.delete('roles/' + RoleId + '/rights/' + Rightsid)

      if (res.meta.status !== 200) {
        this.$message.error('删除失败')
      }

      this.$message.success('已经删除该权限')
      this.getRolesList()
    },

    // 对话框相关
    async showSetRightDialog(role) {
      this.roleId = role.id
      console.log(this.roleId)
      this.defKeys = []
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        this.$message.error('权限列表获取失败')
      }

      this.rightsList = res.data

      this.getLeafKeys(role, this.defKeys)
      this.setRightDialogVisible = true
    },

    // 用递归得到角色最底层的权限（没有children就是权限
    getLeafKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
    },

    async addRights() {
      const key = [...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()]
      const idStr = key.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
      if (res.meta.status !== 200) {
        this.$message.error('修改失败')
      }

      this.$message.success('已修改该用户权限')
      this.getRolesList()

      this.setRightDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.bdbottom {
  border-bottom: 1px solid gainsboro;
}

.bdtop {
  border-top: 1px solid gainsboro;
}
.el-tag {
  margin: 7px;
}

.RolesL {
  display: flex;
  align-items: center;
}
</style>
